package com.atguiju.preparedstatement.crud;

import com.atguiju.bean.Customer;
import com.atguiju.util.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.*;

public class CustomerForQuery {

    @Test
    public void query() {
        String sql = "select id,name,email,birth from customers where id = ?";
        Customer customer = CustomerQuery(sql, 13);
        System.out.println(customer);

    }

    public Customer CustomerQuery(String sql, Object...args) {

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;

        try {
            //1.获取数据库连接
            conn = JDBCUtils.getConnection();

            //2.数据库预编译
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            //3.获取到查询数据
            resultSet = ps.executeQuery();
            //获取数据集的元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            if (resultSet.next()) {
                Customer customer = new Customer();
                for (int i = 0; i < columnCount; i++) {
                    //获取列值
                    Object objectValue = resultSet.getObject(i + 1);
                    //获取每个列的列名getColumnName（）
                    //获取每个列的别名getColumnLabel()
                    String name = metaData.getColumnLabel(i + 1);
                    Field field = Customer.class.getDeclaredField(name);
                    field.setAccessible(true);
                    field.set(customer, objectValue);
                }
                System.out.println(customer);
                return customer;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            JDBCUtils.close(conn, ps, resultSet);
        }
    }
}
